package com.lzp.service.impl;

import com.lzp.mapper.UsersMapper;
import com.lzp.pojo.Users;
import com.lzp.pojo.bo.UserBO;
import com.lzp.service.UserService;
import com.lzp.utils.DateUtil;
import com.lzp.utils.MD5Utils;
import com.lzp.utils.enums.UserSex;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.Map;

/**
 * @author lzp
 * @date 2020/7/19
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private Sid sid;

    private static final String USER_FACE = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public boolean queryUsernameIsExist(String username) {

        // 创建查询条件
        Example userExample = new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();

        criteria.andEqualTo("username", username);

        // 数据库查询
        Users result = usersMapper.selectOneByExample(userExample);

        return result != null;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Users createUser(UserBO userBO) {

        // 使用IdWorker生成全局唯一id，作为主键
        String userId = sid.nextShort();

        Users user = new Users();
        user.setId(userId);
        user.setUsername(userBO.getUsername());
        try {
            user.setPassword(MD5Utils.getMD5Str(userBO.getPassword()));
        } catch (Exception e) {
            // TODO
            e.printStackTrace();
        }
        // 设置默认昵称
        user.setNickname(userBO.getUsername());
        // 设置默认头像
        user.setFace(USER_FACE);
        // 设置默认生日
        user.setBirthday(DateUtil.stringToDate("1990-01-01"));
        // 设置默认性别
        user.setSex(UserSex.SECRET.getCode());
        // 设置注册时间和修改时间
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        usersMapper.insert(user);

        return user;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Users queryUserForLogin(String username, String password) {
        // 创建查询条件
        Example userExample = new Example(Users.class);
        Example.Criteria criteria = userExample.createCriteria();

        // 字段与pojo一致
        criteria.andEqualTo("username", username);
        criteria.andEqualTo("password", password);

        return usersMapper.selectOneByExample(userExample);
    }
}
